package com.melody.android.ui.component;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;

public class CircleImage extends AppCompatImageView {

    private Path clipPath;
    private RectF rectF;
    private Paint ringPaint;
    private float ringWidth;
    private int ringColor;

    public CircleImage(Context context) {
        super(context);
        init();
    }

    public CircleImage(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircleImage(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        clipPath = new Path();
        rectF = new RectF();
        ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        ringWidth = 100f; // 圆环宽度
        ringColor = 0xFF000000; // 圆环颜色，默认为黑色
        setLayerType(LAYER_TYPE_HARDWARE, null); // 开启硬件加速，提高性能
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();

        // 绘制圆形裁剪区域
        rectF.set(0, 0, width, height);
        clipPath.reset();
        clipPath.addOval(rectF, Path.Direction.CW);
        canvas.clipPath(clipPath);

        // 绘制图片
        super.onDraw(canvas);

        // 绘制圆环
        ringPaint.setStyle(Paint.Style.STROKE);
        ringPaint.setStrokeWidth(ringWidth);
        ringPaint.setColor(ringColor);
        canvas.drawCircle(width / 2f, height / 2f, width / 2f - ringWidth / 2f, ringPaint);
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        super.onSizeChanged(width, height, oldWidth, oldHeight);
        rectF.set(0, 0, width, height);
    }

    /**
     * 设置圆环的宽度
     * @param width 圆环宽度
     */
    public void setRingWidth(float width) {
        ringWidth = width;
        invalidate();
    }

    /**
     * 设置圆环的颜色
     * @param color 圆环颜色
     */
    public void setRingColor(int color) {
        ringColor = color;
        invalidate();
    }

}